package com.lee.common.network.net

import android.net.ParseException
import androidx.lifecycle.Observer
import com.google.gson.JsonParseException
import com.lee.common.network.BaseResp
import com.lee.common.network.DataState
import com.lee.common.utils.ToastUtils
import org.json.JSONException
import retrofit2.HttpException
import timber.log.Timber
import java.io.InterruptedIOException
import java.net.ConnectException


private const val TAG = "IStateObserver2"
const val LOGIN_TOKEN_OUT = 401   //token过期
const val LOGIN_NOT_EXIST = 400  //用户不存在
const val Old_Pass_Error = 402   //原密码错误

abstract class ObserverState<T>() : Observer<BaseResp<T>> {

    override fun onChanged(t: BaseResp<T>) {

        Timber.d("onChanged: ${t.dataState}")
        when (t.dataState) {
            DataState.STATE_SUCCESS -> {
                //请求成功，数据不为null
                onDataChange(t.data!!)
            }

            DataState.STATE_EMPTY -> {
                //数据为空
                onDataEmpty()
                onError("暂无数据", -1)

            }
            DataState.STATE_FAILED, DataState.STATE_ERROR -> {
                val error: Throwable? = t.error
                if (error is HttpException) { //网络错误
                    onError("网络异常，请稍候再试...", -1)
                } else if (error is ConnectException) {
                    //无网络连接
                    onError("无网络连接，请打开网络...", -1)
                } else if (error is InterruptedIOException) {
                    //连接超时
                    onError("网络异常，请稍候再试...", -1)
                } else if (error is JsonParseException
                    || error is JSONException
                    || error is ParseException
                ) {
                    //解析错误
                    onError("数据错误，请稍候再试...", -1)
                } else if (t.code == LOGIN_TOKEN_OUT) {
                    onError("您的账号已在其他地方登录！", LOGIN_TOKEN_OUT)
                } else if (t.code == LOGIN_NOT_EXIST) {
                    onError("用户不存在！", LOGIN_TOKEN_OUT)
                } else if (t.code == Old_Pass_Error) {
                    onError("密码错误！", LOGIN_TOKEN_OUT)
                } else {
                    //未知错误
                    onError("未知错误，请稍候再试...", -1)

                }
                Timber.e(error?.message.toString())
            }
            else -> {

            }
        }

    }

    /**
     * 请求数据且数据不为空
     */
    open fun onDataChange(data: T) {

    }

    /**
     * 请求成功，但数据为空
     */
    open fun onDataEmpty() {

    }

    /**
     * 请求错误
     */
    open fun onError(msg: String?, code: Int) {

    }

    /**
     * 弹Toast
     */
    private fun showToast(msg: String) {
        ToastUtils.showShort(msg)
    }
}